package com.bigfans.framework.jms;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

public class JmsReceiverTask implements Runnable{
	
	private volatile boolean runable = true;
	private Connection connection;
	private Session session;
	private String topic;
	private MessageConsumer messageConsumer;
	private MessageListener messageListener;
	private int maxWaitTime = 10000;

	public JmsReceiverTask(Connection connection , String topic , MessageListener messageListener) {
		this.connection = connection;
		this.topic = topic;
		this.messageListener = messageListener;
	}
	
	public void run() {
		try {
			connection.start();
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(topic);
			messageConsumer = session.createConsumer(destination);
			while(runable){
				Message message = messageConsumer.receive(maxWaitTime);
				if(message != null){
					message.acknowledge();
					messageListener.onMessage(message);
				}
			}
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (messageConsumer != null) {
				try {
					messageConsumer.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (session != null) {
				try {
					session.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void stop(){
		this.runable = false;
	}

	public int getMaxWaitTime() {
		return maxWaitTime;
	}

	public void setMaxWaitTime(int maxWaitTime) {
		this.maxWaitTime = maxWaitTime;
	}
	
}
